package com.feiyuan.modules.sys.service.impl;

import com.feiyuan.common.exception.FeiyuanException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feiyuan.common.utils.PageUtils;
import com.feiyuan.common.utils.Query;

import com.feiyuan.modules.sys.mapper.AppVersionDao;
import com.feiyuan.modules.sys.entity.AppVersionEntity;
import com.feiyuan.modules.sys.service.AppVersionService;
import org.springframework.util.CollectionUtils;


@Service("appVersionService")
@Slf4j
public class AppVersionServiceImpl extends ServiceImpl<AppVersionDao, AppVersionEntity> implements AppVersionService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String appInfoId = (String) params.get("appInfoId");
//        IPage<AppVersionEntity> page = this.page(
//                new Query<AppVersionEntity>().getPage(params),
//                new QueryWrapper<AppVersionEntity>().eq(StringUtils.isNotEmpty(appInfoId), "app_info_id", appInfoId).orderByDesc("create_time")
//        );

        IPage<AppVersionEntity> page = baseMapper.selectPages(new Query<AppVersionEntity>().getPage(params), appInfoId);

        return new PageUtils(page);
    }

    @Override
    public String upload(byte[] filebytes, String fileName, long fileSize) {
        long old = System.currentTimeMillis();
        try {
//            String name = "app.apk";
            String path = System.getProperty("user.dir") + "/files/";
            log.info("此文件【{}】的路径是{}", fileName, path);
            File file = new File(path, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            log.info("files文件创建成功!");
            file.setReadable(true);
            file.setWritable(true);
            file.setExecutable(true);
            log.info("开始写入文件1!");
            FileOutputStream os = new FileOutputStream(file);
            log.info("开始写入文件2!");
            os.write(filebytes);
            log.info("开始写入文件3!");
            os.close();
            log.info("开始写入文件4!");
            long now = System.currentTimeMillis();
            log.info("上传共耗时：" + ((now - old) / 1000.0) + "秒");
            return "/files/" + fileName + "@" + fileSize;
        } catch (Exception e) {
            log.error("上传失败...{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void saveAppVersion(AppVersionEntity appVersion) {
        // 保存，检查版本号
        this.checkAppVersion(appVersion.getVersionNum(), appVersion.getAppInfoId());

        if (appVersion.getIsUpgrade().intValue() == 1) {
            AppVersionEntity version = new AppVersionEntity();
            version.setIsUpgrade(0);
            baseMapper.update(version, new QueryWrapper<AppVersionEntity>().eq("app_info_id", appVersion.getAppInfoId()).eq("is_upgrade", 1));
        }

        baseMapper.insert(appVersion);
    }

    @Override
    public void updateAppVersionById(AppVersionEntity appVersion) {
        // 修改，检查版本号
        // 版本号是否改变
        AppVersionEntity appVersionEntity = baseMapper.selectById(appVersion.getId());
        if (!appVersionEntity.getVersionNum().equals(appVersion.getVersionNum())) {
            this.checkAppVersion(appVersion.getVersionNum(), appVersion.getAppInfoId());
        }

        if (appVersionEntity.getIsUpgrade().intValue() != appVersion.getIsUpgrade().intValue()) {
            if (appVersion.getIsUpgrade().intValue() == 1) {
                AppVersionEntity version = new AppVersionEntity();
                version.setIsUpgrade(0);
                baseMapper.update(version, new QueryWrapper<AppVersionEntity>().eq("app_info_id", appVersion.getAppInfoId()).eq("is_upgrade", 1));
            }
        }

        baseMapper.updateById(appVersion);
    }

    @Override
    public Map<String, Object> isUpdate(String versionNum) {
        Map<String, Object> map = new HashMap<>();
        // 查询当前最新的一条
        AppVersionEntity version = baseMapper.selectOne(new QueryWrapper<AppVersionEntity>().eq("is_upgrade", 1));
        if (version != null) {
            String newVersion = version.getVersionNum();
            newVersion = newVersion.replace(".", "");
            String oldVersion = versionNum.replace(".", "");
            if (Integer.valueOf(oldVersion).intValue() < Integer.valueOf(newVersion).intValue()) {
                map.put("isUpgrade", true);
                map.put("downloadUrl", version.getDownloadUrl());
                map.put("fileSize", version.getFileSize());
            }
        } else {
            map.put("isUpgrade", false);
        }
        return map;
    }

    public void checkAppVersion(String appVersion, Long appInfoId) {
        // 1.查询此版本号是否重复了
        List<AppVersionEntity> version = baseMapper.selectList(new QueryWrapper<AppVersionEntity>().eq("version_num", appVersion));
        if (!CollectionUtils.isEmpty(version)) {
            throw new FeiyuanException("版本号重复了!", 500);
        }
        // 2.检测版本号不能小于线上的版本
        AppVersionEntity appVersionEntity = baseMapper.selectOne(new QueryWrapper<AppVersionEntity>().eq("app_info_id", appInfoId).eq("is_upgrade", 1));
        if (appVersionEntity != null) {
            String oldVersion = appVersionEntity.getVersionNum();
            oldVersion = oldVersion.replace(".", "");
            String newVersion = appVersion.replace(".", "");
            if (Integer.valueOf(newVersion) <= Integer.valueOf(oldVersion)) {
                throw new FeiyuanException("版本号不能小于或等于线上的版本号!", 500);
            }
        }
    }

}